#include "string.h"
namespace W1
{
	string::string(const char* str)
		:_size(strlen(str))
	{
		_str = new char[_size + 1];
		strcpy(_str, str);
		_capacity = _size;
	}

	void string::reserve(size_t n)
	{
		if (n > _capacity)
		{
			char* tmp = new char[n + 1];
			strcpy(tmp, _str);
			delete[] _str;
			_str = tmp;
			_capacity = n;
		}

	}

	void string::push_back(char ch)
	{
		if (_size + 1 > _capacity)
		{
			reserve(_capacity == 0 ? 4 : _capacity * 2);
		}
		_str[_size] = ch;
		_size++;
		_str[_size] = '\0';
	}

	void string::append(const char* str)
	{
		size_t len = strlen(str);
		if (len + _size > _capacity)
		{
			size_t newcapacity = _capacity * 2;
			if (len + _size > newcapacity)
			{
				newcapacity = len + _size;
			}
			reserve(newcapacity);
		}
		strcpy(_str + _size, str);
		_size += len;

	}

	void string::insert(size_t pos, size_t n, char ch)
	{
		if (_size + n > _capacity)
		{
			size_t newcpapcity = _capacity * 2;
			if (_size + n > newcpapcity)
			{
				newcpapcity = _size + n;
			}
			reserve(newcpapcity);
		}
		
		size_t end =  _size + n;
		while (end > pos + n - 1)
		{
			_str[end] = _str[end - n];
			end--;
		}

		for (int i = 0; i < n; i++)
		{
			_str[pos + i] = ch;
		}
		_size += n;
	}


	void string::insert(size_t pos, char* str)
	{
		size_t len = strlen(str);
		insert(pos, len, 'x');
		for (int i = 0; i < len ;i++)
		{
			_str[pos + i] = str[i];
		}
	}

	string::~string()
	{
		delete[] _str;
		_str = nullptr;
		_capacity = _size = 0;
	}
}

void test1()
{
	W1::string s1;
	s1.append("hello world");
	//s1.push_back('s');
	cout << s1.c_str();
}